package cn.wanda.bi.sunshine.platform.server.config.redis;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.google.common.collect.Lists;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;


/**
 * Created by wangfupeng1 on 2016-9-5.
 */
@SuppressWarnings({ "rawtypes","unused" })
@Configuration
public class RedisConfig {

	private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    public static final String online = "online";

    @Value("${redis.maxWaitMillis:}")
	private Long maxWaitMillis;
	@Value("${redis.testOnBorrow:}")
	private Boolean testOnBorrow;
	@Value("${redis.testOnReturn:}")
	private Boolean testOnReturn;
	@Value("${redis.maxIdle:}")
	private Integer maxIdle;
	@Value("${redis.maxTotal:}")
	private Integer maxTotal;
	@Value("${redis.minIdle:}")
	private Integer minIdle;
	@Value("${redis.lifo:}")
	private Boolean lifo;
	@Value("${redis.hostAndPorts:}")
	private String hostAndPorts;

	@Bean(name = "jedisPoolConfig")
	public redis.clients.jedis.JedisPoolConfig jedisPoolConfig() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxIdle(maxIdle);
		jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
		jedisPoolConfig.setTestOnBorrow(testOnBorrow);
		jedisPoolConfig.setMaxTotal(maxTotal);
		jedisPoolConfig.setMinIdle(minIdle);
		jedisPoolConfig.setLifo(lifo);
		return jedisPoolConfig;
	}

	@Bean(name = "shardedJedisPool")
	public redis.clients.jedis.ShardedJedisPool shardedJedisPool(@Qualifier("jedisPoolConfig") JedisPoolConfig jedisPoolConfig) {
		List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
		String[] hostAndPortsArray = hostAndPorts.split(",");
		Lists.newArrayList(hostAndPortsArray).forEach(host -> {
			String[] hostArray = host.split(":");
			String hostAddress = hostArray[0];
			Integer port = Integer.valueOf(hostArray[1]);
			JedisShardInfo info = new JedisShardInfo(hostAddress, port);
			shards.add(info);
		});
		ShardedJedisPool shardedJedisPool = new ShardedJedisPool(jedisPoolConfig, shards);
		return shardedJedisPool;
	}
	
	@Bean(name = "keySerializer")
	public RedisSerializer keySerializer() {
		return  new StringRedisSerializer();
	}
	

	@Bean(name = "valueSerializer")
	public RedisSerializer valueSerializer() {
		return new JdkSerializationRedisSerializer();
	} 

}

